package servlet;

import exception.ValidationException;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
//import org.apache.commons.fileupload.FileUpload;
//import stateless.Event.EventSessionRemote;

//import java.util.List;
//import java.util.Iterator;
//import java.io.File;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
/**
* Mise en ligne d'un fichier.
* 
* <!Cette classe ne sert pas, on la laisse au cas on veut sauvegarder les images
* dans un repertoire et un base des donnes>
* @author : jgineste
*/
@SuppressWarnings("deprecation")
public class UploadPicture extends HttpServlet {

	private static final long serialVersionUID = 5851603961297945564L;
	//@EJB
    //private EventSessionRemote eventSessionBean;

    public UploadPicture() {
        super();
    }


    protected void processRequest(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
        //HttpSession session = req.getSession();
       // User u =  (User) session.getAttribute("user");
        String user = (String)req.getSession().getAttribute("id");
        System.out.println("User: "+ user);
        if (!user.isEmpty()) {
            try{
                String adressePicture = null;
                String idEvent = null;
                String redir = null;
                FileItemFactory factory = new DiskFileItemFactory();
           ServletFileUpload upload = new ServletFileUpload(factory);
           List<?> items = null;
           try {
                   items = upload.parseRequest(req);
           } catch (Exception e) {
                   //e.printStackTrace();
           }
           Iterator<?> itr = items.iterator();
           while (itr.hasNext()) {
           FileItem item = (FileItem) itr.next();
           
                   try {
                           String itemName = item.getName();
                           if (item.isFormField()) {
                            if (item.getFieldName().equals("idevent")) {
                                idEvent = item.getString();
                            }
                        }else{
                           if ((item.getName().endsWith("png")) || ((item.getName().endsWith("jpg"))) || ((item.getName().endsWith("gif")))){
                           
                           adressePicture = "Pictures/" + item.getName();    
                           File savedFile = new File(getServletContext().getRealPath("/")+"Pictures/"+itemName);
                           item.write(savedFile);
                                redir = "index.jsp";
                           }
                           
                   }
                                              
                   } catch (Exception e1) {
                           e1.printStackTrace();
                   }
    
           
           }
                   // eventSessionBean.definirAdressePicture(adressePicture, idEvent);
                    req.setAttribute("message","Votre image a bien été ajoutée.");
                    req.getRequestDispatcher(redir).forward(req, res);

            } catch (ValidationException v) {
                req.setAttribute("wrongextension", v.getMessage());
                try {
                    req.getRequestDispatcher("AddPhoto.jsp").forward(req, res);
                } catch (ServletException ex) {
                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
                }
            } catch(Exception e) {
                try {
                    req.getRequestDispatcher("AddPhoto.jsp").forward(req, res);
                } catch (ServletException ex) {
                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(UploadPicture.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        } else {
            req.setAttribute("message", "Vous devez être connecté pour ajouter un event");
            req.getRequestDispatcher("index.jsp").forward(req, res);
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        processRequest(req, res);
    }
    
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        processRequest(req, res);
    }
}